package cn.innosmart.aq.isp;

import android.os.Build;
import android.util.Log;

import com.tutk.p2p.ConnectionManager;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Locale;

import cn.innosmart.aq.BuildConfig;
import cn.innosmart.aq.application.AQApplication;
import cn.innosmart.aq.manager.ContactsManager;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.SplashActivity;

public class ISPTool {
    private static onISPCallBack callback;
    private MqttClient mqttClient;
    private MqttConnectOptions mMqttOptions;
    private String mqttHost = null;
    private String mqttUserName = "admin";
    private String mqttPassWord = "password";
    private String mMQTTClientID;
    private String sub_topic = "cn.innosmart.isp/sub";
    private String unSub_topic = "cn.innosmart.isp/unsub";
    private String expired_topic = "cn.innosmart.isp/event/expired";
    private String strMessage;
    private MqttMessage message;

    private ISPTool() {
        initMQTT();
    }

    public static ISPTool getInstance() {
        return ISPToolInstance.isptool;
    }

    /**
     * 获取设备型号
     *
     * @return
     */
    @SuppressWarnings("static-access")
    public static String getDeviceName() {
        return new Build().MODEL;
    }


    /**
     * 初始化ISP
     */
    private void initMQTT() {
        mqttHost = "tcp://mqtt.innosmart.cn:1883";
        Log.v("Tag", "initMQTT. mqttHost = " + mqttHost);
        try {
            if (null == mMQTTClientID) {
                mMQTTClientID = AQApplication.getInstance().getMqttClientId();
                mMQTTClientID = mMQTTClientID.substring(0, mMQTTClientID.length() - 4) + "_ISP";
//                mMQTTClientID=mMQTTClientID.replace(mMQTTClientID.charAt(mMQTTClientID.length()-4)+"","新字符");
            }
            mqttClient = new MqttClient(mqttHost, mMQTTClientID, new MemoryPersistence());
            System.out.println("mMQTTClientID=" + mMQTTClientID);
            mMqttOptions = new MqttConnectOptions();
            mMqttOptions.setCleanSession(true);
            mMqttOptions.setUserName(mqttUserName);
            mMqttOptions.setPassword(mqttPassWord.toCharArray());
            mMqttOptions.setConnectionTimeout(10);
            mMqttOptions.setKeepAliveInterval(20);
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {

                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    Log.v("Tag", "deliveryComplete: " + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置ISP的回调函数
     *
     * @param on
     */
    private void setISPCallBack(onISPCallBack on) {
        callback = on;
    }

    /**
     * 订阅
     *
     * @param type
     * @param did
     * @param addr
     */
    public void subscribe(String type, String did, String prefix, String addr) {
        initData(type, did, prefix, addr);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mqttClient.connect(mMqttOptions);
                    try {
                        mqttClient.publish(sub_topic, message);
                        if (callback != null) {
                            callback.onSuccess(0, 1);
                        }
                        try {
                            mqttClient.disconnect();
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                    } catch (MqttException e) {
                        if (callback != null) {
                            callback.onFailed(-14, -1);
                        }
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    if (callback != null) {
                        callback.onFailed(-14, -1);
                    }
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 报警后的清除事件方法
     *
     * @param uids
     * @param timestamp
     */
    public void changeEvent(final ArrayList<String> uids, final long timestamp) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mqttClient.connect(mMqttOptions);
                    for (String uid : uids) {
                        String eventMessage = uid + "," + timestamp;
                        MqttMessage mqttMessage = new MqttMessage(eventMessage.getBytes());
                        try {
                            System.out.println("ChangeISp=" + mqttMessage.toString());
                            mqttClient.publish(expired_topic, mqttMessage);
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        mqttClient.disconnect();
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void changeEvent(String uid, long timestamp) {
        String eventMessage = uid + "," + timestamp;
        final MqttMessage mqttMessage = new MqttMessage(eventMessage.getBytes());
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mqttClient.connect(mMqttOptions);
                    try {
                        mqttClient.publish(expired_topic, mqttMessage);
                        try {
                            mqttClient.disconnect();
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 更新ISP信息
     *
     * @param type          * BuildConfig.ISPFLAG编译时带入的变量，根据不同的Flavor会编译成不同变量
     * @param did
     * @param isSubscribe   yes订阅  no取消订阅
     * @param addr
     * @param onIspCallBack 订阅回调函数
     */
    public void updateISP(String type, String did, String isSubscribe, String prefix,  String addr, onISPCallBack onIspCallBack) {
        setISPCallBack(onIspCallBack);
        if (isSubscribe.equals("yes")) {
            subscribe(type, did, prefix, addr);
        } else {
            unSubscribe(type, did, prefix, addr);
        }
    }


    /**
     * 取消订阅
     *
     * @param type type类型 xinge 信鸽 tel 电话 sms 短信
     * @param did
     * @param addr
     */
    public void unSubscribe(String type, String did, String prefix, String addr) {
        initData(type, did, prefix, addr);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mqttClient.connect(mMqttOptions);
                    try {
                        mqttClient.publish(unSub_topic, message);
                        if (callback != null) {
                            callback.onSuccess(0, 0);
                        }
                        try {
                            mqttClient.disconnect();
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    if (callback != null) {
                        callback.onFailed(-14, -1);
                    }
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 初始化订阅数据，拼接address
     * BuildConfig.ISPFLAG编译时带入的变量，根据不同的Flavor会编译成不同变量
     *
     * @param type type类型 xinge 信鸽 tel 电话 sms 短信
     * @param did
     * @param addr
     */
    private void initData(String type, String did, String prefix, String addr) {
        String uiLang = "aq_cn";
        if(SplashActivity.lang.equals("zh_TW") ) {
            uiLang = "aq1";
        }
        if (type.equals("xinge")) {
            addr = "xg:" + uiLang + ":android:" + addr;
        } else if (type.equals("tel")) {
            addr = prefix + addr;
            addr = "tel:" + uiLang + ":ios:" + addr;
        } else if (type.equals("sms")) {
            addr = prefix + addr;
            addr = "sms:" + uiLang + ":ios:" + addr;
        } else {
            addr = type + ":" + uiLang + ":android:" + addr;
        }
        //获取手机号
        JSONObject loginJson = SharedUtil.getInstance().readLoginInfo();
        String username = null;
        try {
            username = loginJson.getString("username");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //拼接address
        if (username != null) {
            addr = addr + ":" + getDeviceName() + ":" + ConnectionManager.getInstance().getCurrentConnectionEntity().getUid() + ":" + username;
        } else {
            addr = addr + ":" + getDeviceName() + ":" + ConnectionManager.getInstance().getCurrentConnectionEntity().getUid() + ":" + SharedUtil.getInstance().readUserId();
        }
        //简体版
        addr = addr + ":zh_cn";
        System.out.println("addr=" + addr);
        JSONObject jsonSubTopic = new JSONObject();
        try {
            jsonSubTopic.put("did", did);
            jsonSubTopic.put("addr", addr);
            jsonSubTopic.put("from", mMQTTClientID);
            strMessage = jsonSubTopic.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        message = new MqttMessage(strMessage.getBytes());
    }

    public interface onISPCallBack {
        void onSuccess(int resultcode, int xingeId);

        void onFailed(int resultcode, int xingeId);
    }

    private static class ISPToolInstance {
        private static final ISPTool isptool = new ISPTool();

    }
}
